import { Controller } from 'egg';

const userRule = {
  username: {
    type: 'string',
    required: true,
    allowEmpty: false,
  },
  password: {
    type: 'string',
    required: true,
    allowEmpty: false,
  },
  nickname: {
    type: 'string',
    required: false,
    allowEmpty: true,
  },
  atavar: {
    type: 'string',
    required: false,
    allowEmpty: true,
  },
  phone: {
    type: 'string',
    required: false,
    allowEmpty: true,
    format: /^\d+$/,
  },
  address: {
    type: 'string',
    required: false,
    allowEmpty: true,
  },
};
const registerRule = {
  username: {
    type: 'string',
    required: true,
    allowEmpty: false,
  },
  password: {
    type: 'string',
    required: true,
    allowEmpty: false,
  },
  companyName: {
    type: 'string',
    required: false,
    allowEmpty: true,
  },
  scale: {
    type: 'number',
    required: false,
    allowEmpty: true,
  },
  location: {
    type: 'object',
    required: false,
    allowEmpty: true,
  },
};
const dimissionRule = {
  userids: {
    type: 'array',
    required: true,
    allowEmpty: false,
  },
};
const createRule = {
  username: {
    type: 'string',
    required: true,
    allowEmpty: false,
  },
  gender: {
    type: 'number',
    required: false,
    allowEmpty: true,
  },
  phone: {
    type: 'string',
    required: true,
    allowEmpty: true,
    format: /^\d+$/,
  },
  email: {
    type: 'string',
    required: false,
    allowEmpty: true,
  },
  orgId: {
    type: 'string',
    required: false,
    allowEmpty: true,
  },
  role: {
    type: 'string',
    required: false,
    allowEmpty: true,
  },
  empno: {
    type: 'string',
    required: true,
    allowEmpty: false,
  },
  jobTitle: {
    type: 'string',
    required: false,
    allowEmpty: true,
  },
  hiredate: {
    type: 'string',
    required: false,
    allowEmpty: true,
  },
};
const saveRule = {
  userid: {
    type: 'string',
    required: true,
    allowEmpty: false,
  },
  username: {
    type: 'string',
    required: true,
    allowEmpty: false,
  },
  gender: {
    type: 'number',
    required: false,
    allowEmpty: true,
  },
  phone: {
    type: 'string',
    required: true,
    allowEmpty: true,
    format: /^\d+$/,
  },
  email: {
    type: 'string',
    required: false,
    allowEmpty: true,
  },
  orgId: {
    type: 'string',
    required: false,
    allowEmpty: true,
  },
  role: {
    type: 'string',
    required: false,
    allowEmpty: true,
  },
  empno: {
    type: 'string',
    required: true,
    allowEmpty: false,
  },
  jobTitle: {
    type: 'string',
    required: false,
    allowEmpty: true,
  },
  hiredate: {
    type: 'string',
    required: false,
    allowEmpty: true,
  },
};
const updateInfoRule = {
  key: {
    type: 'string',
    required: true,
    allowEmpty: false,
  },
};
const updatePasswordRule = {
  password: {
    type: 'string',
    required: true,
    allowEmpty: false,
  },
  newPassword: {
    type: 'string',
    required: true,
    allowEmpty: false,
  },
};
export default class User extends Controller {
  async login() {
    const { app, ctx, service, logger } = this;
    const params = Object.assign({}, ctx.request.body);
    try {
      ctx.validate(userRule, params);
    } catch (err: any) {
      logger.error(new Error(err.code));
      ctx.body = ctx.response.paramError(err.errors);
      return false;
    }
    const userInfo = await service.user.getUserByName(params);
    if (!userInfo) {
      ctx.body = ctx.response.basicAuthError('账号或密码错误');
      return;
    }
    // token 生成
    const token = app.jwt.sign(
      {
        userid: userInfo.userid,
        exp: Math.floor(Date.now() / 1000) + 24 * 60 * 60 * 7, // token 有效期为 7 天
      },
      app.config.jwt.secret,
    );

    ctx.cookies.set('token', token, {
      signed: false,
    });
    ctx.body = ctx.response.success(userInfo);
  }

  async logout() {
    const { ctx } = this;
    ctx.cookies.set('token', null, {
      signed: false,
    });
    ctx.body = ctx.response.success();
  }
  // 获取个人信息
  async getUserInfo() {
    const { ctx, app } = this;
    const userid = await ctx.helper.getUserid(ctx);
    // 通过 token 带过来的 username 获取到个人信息
    const userInfo = await ctx.service.user.getUserById({
      userid,
    });
    ctx.body = ctx.response.success(userInfo);
  }

  async getUserListByDept() {
    const { ctx, service } = this;
    const params = Object.assign({}, ctx.query, ctx.params);
    const userInfo = await service.user.getUserListByDept(params);
    ctx.body = ctx.response.success(userInfo);
  }

  // 注册的都是公司身份，默认为系统管理员
  async register() {
    const { ctx, logger } = this;
    const userid = 'user_' + ctx.helper.getUuid();
    const companyId = 'company_' + ctx.helper.getUuid();
    const params = Object.assign({ userid, companyId }, ctx.request.body);
    try {
      ctx.validate(registerRule, params);
    } catch (err: any) {
      logger.error(new Error(err.code));
      ctx.body = ctx.response.paramError(err.errors);
      return false;
    }
    const result = await ctx.service.user.register(params);
    if (result) {
      ctx.body = ctx.response.success();
    } else {
      ctx.body = ctx.response.systemError('注册失败');
    }
  }

  async dimission() {
    const { ctx, service, logger } = this;
    const params = Object.assign({}, ctx.request.body);
    try {
      ctx.validate(dimissionRule, params);
    } catch (err: any) {
      logger.error(new Error(err.code));
      ctx.body = ctx.response.paramError(err.errors);
      return false;
    }
    const res = await service.user.dimission(params);
    ctx.body = ctx.response.success(res);
  }

  async create() {
    const { ctx, service, logger } = this;
    const params = Object.assign({}, ctx.request.body);
    try {
      ctx.validate(createRule, params);
    } catch (err: any) {
      logger.error(new Error(err.code));
      ctx.body = ctx.response.paramError(err.errors);
      return false;
    }
    const res = await service.user.create(params);
    ctx.body = ctx.response.success(res);
  }

  async save() {
    const { ctx, service, logger } = this;
    const params = Object.assign({}, ctx.request.body);
    try {
      ctx.validate(saveRule, params);
    } catch (err: any) {
      logger.error(new Error(err.code));
      ctx.body = ctx.response.paramError(err.errors);
      return false;
    }
    const res = await service.user.save(params);
    ctx.body = ctx.response.success(res);
  }

  async updateInfo() {
    const { ctx, service, logger } = this;
    const userid = await ctx.helper.getUserid(ctx);
    const params = Object.assign({ userid }, ctx.request.body);
    try {
      ctx.validate(updateInfoRule, params);
    } catch (err: any) {
      logger.error(new Error(err.code));
      ctx.body = ctx.response.paramError(err.errors);
      return false;
    }
    const res = await service.user.updateInfo(params);
    ctx.body = ctx.response.success(res);
  }

  async updatePassword() {
    const { ctx, service, logger } = this;
    const userid = await ctx.helper.getUserid(ctx);
    const params = Object.assign({ userid }, ctx.request.body);
    try {
      ctx.validate(updatePasswordRule, params);
    } catch (err: any) {
      logger.error(new Error(err.code));
      ctx.body = ctx.response.paramError(err.errors);
      return false;
    }
    const res = await service.user.updatePassword(params);
    ctx.body = ctx.response.success(res);
  }
}
